package app

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go-admin/global"
)

// 错误结果
type ValidError struct {
	Key     string
	Message string
}

type ValidErrors []*ValidError

func (v *ValidError) Error() string {
	return v.Message
}

func (v ValidErrors) Errors() []string {
	var errs []string
	for _, err := range v {
		errs = append(errs, err.Error())
	}
	return errs
}

// 绑定并校验
func BindAndValid(c *gin.Context, v interface{}) (bool, ValidErrors) {
	var errs ValidErrors
	err := c.ShouldBind(v)
	if err != nil {
		errors, ok := err.(validator.ValidationErrors)
		if !ok {
			return false, nil
		}
		for key, value := range errors.Translate(global.Trans) {
			errs = append(errs, &ValidError{
				Key:     key,
				Message: value,
			})
		}
		return false, errs
	}
	return true, nil
}
